package com.wyq.new_springboot.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wyq.new_springboot.entity.TUser;
import com.wyq.new_springboot.mapper.TUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    TUserMapper tUserMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            response.sendRedirect("/test/login");
            return false;
        }
        //测试如果禁用cookie，测试能不能取到session
        TUser user = (TUser) request.getSession().getAttribute("user");
        if(user !=null){
            System.out.println("session的用户============"+user.toString());
        }else{
            System.out.println("session没有取到===========");
        }
        QueryWrapper<TUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.notIn("id",-1);
        List<TUser> tUsers = tUserMapper.selectList(queryWrapper);
        tUsers.forEach(System.out::println);
        for (Cookie c:cookies) {
            if(c.getName().equals("userName")){
                String userName=c.getValue();
                for (TUser tUser : tUsers) {
                    if(tUser.getUserName().equals(userName)){
                        return true;
                    }
                }
            }
        }
        response.sendRedirect("/test/login");
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
